package com.dhy.socket;

import com.dhy.socket.handler.DistributeClientInfoHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * <p>
 * 副实例
 * </p>
 *
 * @author 大忽悠
 * @create 2022/7/5 10:14
 */
@Slf4j
public class DistributedClientSocket {
    private final Bootstrap client;
    private final NioEventLoopGroup worker;
    private final DistributeClientInfoHandler clientInfoHandler;
    private Channel ch;

    public DistributedClientSocket() {
        this.client = new Bootstrap();
        this.worker = new NioEventLoopGroup();
        this.clientInfoHandler = new DistributeClientInfoHandler();
    }

    /**
     * 启动副实例
     */
    public void start() throws InterruptedException {
        ch=client.group(worker)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(clientInfoHandler);
                    }
                })
                .connect(new InetSocketAddress("localhost", 18080))
                .sync()
                .channel();

        log.info("副本实例启动完毕!");
        //写事件
        clientInfoHandler.channelWrite(ch);
        //关闭回调
        ch.closeFuture().sync();
        log.info("结束运行!");
        close();
    }


    /**
     * 关闭主实例
     */
    public void close() {
        worker.shutdownGracefully();
        ch.close();
    }
}
